import axios from 'axios';
// 进度条
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
Nprogress.configure({
    showSpinner: false
});
// 超时处理
axios.defaults.timeout = 30 * 1000;
// axios.defaults.withCredentials = false;

// axios.defaults.baseURL = '/api/'
// http request 拦截器
axios.interceptors.request.use(
    config => {
        const token = sessionStorage.getItem('token') || ''
        Nprogress.start()
        if (token) {
            // 说明用户已经登陆
            // 说明token值放到请求头当中去
            config.headers['token'] = token
            // config.headers['userName'] = sessionStorage.getItem('username')
            // config.headers['userId'] = sessionStorage.getItem('userid')
            // ip地址
            // config.headers['clientIp'] = sessionStorage.getItem('ip')
            // mac地址
            // config.headers['clientId'] = null

        }
        return config;
    }
)
// http response 拦截器
axios.interceptors.response.use(
    response => {
        Nprogress.done()
        return response;
    },
    // error => {
    //     Nprogress.done()
    //     return Promise.reject(error);
    // }
);
let http = {
    request(opt) {
        return new Promise((resolve, reject) => {
            axios({
                    url: opt.url,
                    method: opt.method || 'post',
                    params: opt.params || '',
                    data: opt.data || '',
                    // formData: opt.formData || '',
                    xhrFields: {
                        withCredentials: false
                    },
                    headers: opt.headers || {}
                })
                .then(res => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                })
        })
    }
}
export default http